package com.example.lirisheng.springbootfinalexperiment.security;

import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Component;

import javax.persistence.criteria.CriteriaBuilder;
import java.util.Collection;
import java.util.Iterator;

/**
 * @author : DGUT.YE
 * @date : 2020/09/15
 **/
@Component
public class CustomDesicionManger implements AccessDecisionManager {

    /**
     *
     * @param authentication 用户的角色
     * @param object
     * @param configAttributes  你filter里面返回的Role 即 url需要的角色
     * @throws AccessDeniedException
     * @throws InsufficientAuthenticationException
     */
    @Override
    public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes) throws AccessDeniedException, InsufficientAuthenticationException {


        for (ConfigAttribute configAttribute : configAttributes) {
            String needRole = configAttribute.getAttribute();

            if ("ROLE_LOGIN".equals(needRole)){
                //没有该路径
                throw new AccessDeniedException("无效的访问路径");
            }

            // 这里是权限的判断  决定于业务逻辑  这个菜单所需要的权限 是 都要有 还是只要有一个就可以了呢?
            // 这里的逻辑就是有一个就可以了
            Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
            System.out.println("用户所有的权限:"+authorities);
            for (GrantedAuthority authority : authorities) {
                if (authority.getAuthority().equals(needRole)){
                    return;
                }
            }
        }
        throw  new AccessDeniedException("权限不足，请联系管理员!");
    }

    @Override
    public boolean supports(ConfigAttribute attribute) {
        return true;
    }

    @Override
    public boolean supports(Class<?> clazz) {
        return true;
    }
}
